package com.flowershop.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.flowershop.config.FileUploadConfig;
import com.flowershop.utils.FileUtils;

@RestController
@RequestMapping("/api/upload")
@CrossOrigin
public class FileController {

    @Autowired
    private FileUploadConfig fileUploadConfig;

    @PostMapping
    public ResponseEntity<Map<String, Object>> upload(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "type", defaultValue = "image") String type) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 检查文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                result.put("code", 400);
                result.put("message", "只能上传图片文件");
                return ResponseEntity.badRequest().body(result);
            }
            
            // 保存文件
            String relativePath = FileUtils.saveFile(file, fileUploadConfig.getPath(), type);
            String url = fileUploadConfig.getUrlPrefix() + "/" + relativePath;
            
            result.put("code", 200);
            result.put("message", "上传成功");
            result.put("data", Map.of("url", url));
            return ResponseEntity.ok(result);
            
        } catch (IOException e) {
            result.put("code", 500);
            result.put("message", "文件上传失败：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
} 